package com.example.okhttpdemo.api;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class Api {
    private static OkHttpClient client;
    private static String requestUrl;
    private static Map<String, Object> mParams;
    public static Api api = new Api();

    public Api() {

    }

    public static Api config(String url, Map<String, Object> params) {
        client = new OkHttpClient.Builder().connectTimeout(10, TimeUnit.SECONDS)
                .writeTimeout(10, TimeUnit.SECONDS).build();

        requestUrl = ApiConfig.BASE_URL + url;
        mParams = params;
        return api;
    }

    /**
     * get同步请求
     *
     * @param callback
     */
    public void get(ResponseCallback callback) {

        OkHttpClient okHttpClient = new OkHttpClient();
        final Request request = new Request.Builder()
                .url(requestUrl)
                .build();
        final Call call = okHttpClient.newCall(request);

        try {
            Response response = call.execute();
            String result = response.body().string();
            callback.OnSuccess(result);
        } catch (IOException e) {
            callback.OnFailure(e);
        }


    }

    /**
     * get异步请求
     *
     * @param callback
     */
    public void getAsync(ResponseCallback callback) {
        if(mParams!=null){
            requestUrl+=getUrlParams(mParams);
        }

        OkHttpClient okHttpClient = new OkHttpClient();
        final Request request = new Request.Builder()
                .url(requestUrl)
                .get()//默认就是GET请求，可以不写
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                callback.OnFailure(e);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String result = response.body().string();
                callback.OnSuccess(result);
            }
        });
    }

    /**
     * post异步请求，请求参数：
     *
     * @param callback
     */
    public void postAsyc(ResponseCallback callback) {
        JSONObject jsonObject = new JSONObject(mParams);
        String jsonStr = jsonObject.toString();
        RequestBody requestBody =
                RequestBody.create(MediaType.parse("application/json;charset=utf-8"), jsonStr);
        Request request = new Request.Builder()
                .url(requestUrl)
                .addHeader("contentType", "application/json;charset=utf-8")
                .post(requestBody)
                .build();
        final Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

                callback.OnFailure(e);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String result = response.body().string();
                callback.OnSuccess(result);

            }
        });


    }

    /**
     * post异步上传文件，使用流方式上传
     *
     * @param callback 回调信息
     * @param file 文件
     */
    public void postFile(ResponseCallback callback,File file){
        RequestBody fileBody = RequestBody.create(MediaType.parse("application/octet-stream"), file);
        RequestBody requestBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("application/octet-stream", file.getName(), fileBody)
                .build();
        Request request = new Request.Builder()
                .url(requestUrl)//登录地址
                .post(requestBody)
                .build();
        client.newCall(request).enqueue(new Callback() {

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String result=response.body().string();
                callback.OnSuccess(result);
            }

            @Override
            public void onFailure(Call arg0, IOException e) {
                // TODO Auto-generated method stub
                callback.OnFailure(e);

            }

        });
    }
    /**
     * 上传文件。
     * @param callback 回调信息
     * @param formFields 表单信息
     * @param files 文件信息
     */
    public void postMultipart(ResponseCallback callback, Map<String, String> formFields, File[] files) throws Exception {

        MultipartBody.Builder bodyBuilder = new MultipartBody.Builder()
                .setType(MultipartBody.FORM);

        for (Map.Entry<String, String> field: formFields.entrySet()) { // 添加表单信息
            bodyBuilder.addFormDataPart(field.getKey(), field.getValue());
        }
        MediaType mediaType = MediaType.parse("text/plain");
        for (File file: files) { // 添加文件
            bodyBuilder.addFormDataPart("files", file.getName(),
                    RequestBody.create(mediaType, file));
        }
        Request request = new Request.Builder()
                .url(requestUrl)
                .post(bodyBuilder.build())
                .build();
        client.newCall(request).enqueue(new Callback() {

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String result=response.body().string();
                callback.OnSuccess(result);
            }

            @Override
            public void onFailure(Call arg0, IOException e) {
                // TODO Auto-generated method stub
                callback.OnFailure(e);

            }

        });

    }


    private  String getUrlParams(Map<String,Object> params){
        StringBuilder stringBuilder=new StringBuilder();

        stringBuilder.append("?");
        Iterator<Map.Entry<String,Object>> iterator=params.entrySet().iterator();
        while (iterator.hasNext()){
            Map.Entry<String,Object> next=iterator.next();
            String key=next.getKey();
            String value=(String)next.getValue();
            stringBuilder.append(key);
            stringBuilder.append("=");
            stringBuilder.append(value);
            if(iterator.hasNext()){
                stringBuilder.append("&");
            }
        }

        return stringBuilder.toString();
    }




}
